#!/usr/bin/env python
#-*- coding:UTF-8 -*-
#####################################################
# Author: Jiaion - jiaion21@gmail.com
# Last modified:	2011-04-26 21:58
# Filename:	Jredis.py
#####################################################

import redis
import settings
import cPickle as pickle

RDCONFIG = settings.REDIS

RED = redis.Redis(host=RDCONFIG['HOST'], port=RDCONFIG['PORT'], db=RDCONFIG['DB'], socket_timeout=3)

def _utf8(value):
    if isinstance(value, unicode):
        return value.encode('utf-8')
    assert isinstance(value, str)
    return value

def lpushs(key, value):
    """redis LPUSH command"""
    key = _utf8(key)
    value = pickle.dumps(value)
    return RED.lpush(key, value)

def lpush(key, value):
    """redis LPUSH command"""
    key = _utf8(key)
    return RED.lpush(key, value)

def lpops(key):
    """redis lpop command"""
    key = _utf8(key)
    try :
        obj = pickle.loads(RED.lpop(key))
    except TypeError:
        obj = None
    return obj

def lpop(key):
    """redis lpop command"""
    key = _utf8(key)
    return RED.lpop(key)

def llen(key):
    """redis LLEN command"""
    key = _utf8(key)
    return RED.llen(key)

def lrem(key, value):
    """redis LREM command"""
    key = _utf8(key)
    return RED.lrem(key, value)

def lrange(key, start, stop):
    """redis LRANGE command"""
    key = _utf8(key)
    return RED.lrange(key, start, stop)

def sets(key, value):
    """redis SET command"""
    key = _utf8(key)
    value = pickle.dumps(value)
    return RED.set(key, value)

def set(key, value):
    """redis SET command"""
    key = _utf8(key)
    return RED.set(key, value)

def gets(key):
    """redis GET command"""
    key = _utf8(key)
    obj = pickle.loads(RED.get(key))
    return obj

def get(key):
    """redis GET command"""
    key = _utf8(key)
    return RED.get(key)
